﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class Connection
    {
        SqlConnection conn = new SqlConnection();
        public Connection()
        {
            conn.ConnectionString = "server=(local);database=QLVT;Integrated Security=True";
            if (conn.State == ConnectionState.Closed)
                conn.Open();
        }
        public DataTable LoadData(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adapter.Fill(dt);
            return dt;

        }
        public int Update(string sql, string[] name, object[] value, int nparameter)
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            for (int i = 0; i < nparameter; i++)
            {
                cmd.Parameters.AddWithValue(name[i], value[i]);

            }
            return cmd.ExecuteNonQuery();

        }

        public bool ExcuteNonQuery(string sql)
        {
            try
            {
                SqlConnection cn = new SqlConnection(sql);
                cn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = cn;
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                cn.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }

        #region "Lấy mã cuối cùng"
        public string GetLastID(string nameTable, string nameFiled)
        {

            string sql = "SELECT TOP 1 " + nameFiled + " FROM " + nameTable + " ORDER BY " + nameFiled + " DESC";
            DataTable dt = LoadData(sql);
            return dt.Rows[0][nameFiled].ToString();

        }
        #endregion
    }
}
